<template>
  <el-drawer
    ref="drawerRef"
    size="100%"
    v-model="visible"
    title="定价核算"
    direction="rtl"
    :before-close="handleBeforeClose"
  >
    <!-- 基础信息表单 -->
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      style="margin-left: 10px"
    >
      <el-row :gutter="10">
        <el-col :span="16">
          <el-row :gutter="10">
            <el-col :span="5">
              <el-form-item label="链接id" prop="linkId">
                <el-input v-model.number="form.linkId" placeholder="请输入链接id"/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="款式编码" prop="iid">
                <el-input v-model="form.iid" placeholder="请输入款式编码"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="链接名称" prop="linkName">
                <el-input v-model="form.linkName" placeholder="请输入链接名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="链接归属人" prop="userId">
                <CascaderUser v-model="form.userId"/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="店铺" prop="shopId">
                <select-basic-shop v-model="form.shopId"/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label="操作">
                <el-button type="primary" @click="saveLink">
                  <Icon icon="ep:refresh"/>
                  保存链接
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>

        <!-- 统计卡片 -->
        <el-col :span="8">
          <div class="card" style="height: 100%">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-statistic :value="form.sales">
                  <template #title>
                    <span>链接销售额</span>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="8">
                <el-statistic :value="form.profit">
                  <template #title>
                    <span>链接利润</span>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="8">
                <el-statistic :value="form.profitMargin">
                  <template #title>
                    <span>链接利润率%</span>
                  </template>
                  <template #suffix>
                    <span>%</span>
                  </template>
                </el-statistic>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </el-form>


    <!-- SKU 表格区域 -->
    <el-card class="box-card" style="margin-top: 16px">
      <template #header>
        <el-row :gutter="10" style="display: flex; align-items: center;">
          <el-col :span="8">
            <el-button type="primary" plain
                       @click="openGoodsDialog">
              <Icon icon="ep:circle-plus"/>
              按商品编码添加sku
            </el-button>
            <el-button type="primary" plain
                       @click="openCombineDialog">
              <Icon icon="ep:refresh"/>
              按组合编码添加sku
            </el-button>
            <!--            <el-button type="primary"  plain-->
            <!--                       @click="openBatchDialog">-->
            <!--              <Icon icon="ep:magic-stick" />-->
            <!--              批量处理-->
            <!--            </el-button>-->
          </el-col>

          <!-- 优惠参数输入 -->
          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="fixedValue1"/>
              <span class="bar"></span>
              <label>{{ fixedName1 }}</label>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="fixedValue2"/>
              <span class="bar"></span>
              <label>{{ fixedName2 }}</label>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="fixedValue3"/>
              <span class="bar"></span>
              <label>{{ fixedName3 }}</label>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="rateValue1"/>
              <span class="bar"></span>
              <label>{{ rateName1 }}</label>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="rateValue2"/>
              <span class="bar"></span>
              <label>{{ rateName2 }}</label>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="rateValue3"/>
              <span class="bar"></span>
              <label>{{ rateName3 }}</label>
            </div>
          </el-col>

          <el-col :span="2">
            <div class="group">
              <input required type="text" class="input" v-model="discount"/>
              <span class="bar"></span>
              <label>{{ discountName }}</label>
            </div>
          </el-col>

          <el-col style="flex: 1; text-align: right;">
            <el-button type="text" @click="clearAllSku">清空</el-button>
          </el-col>
        </el-row>
      </template>

      <!-- SKU 表格 -->
      <el-table
        v-model:current-row-key="currentRow"
        :data="skuList"
        style="width: 100%"
        border
        max-height="650px"
        :cell-style="handleCellStyle"
        :header-cell-style="handleHeaderCellStyle"
        size="small"
      >
        <!--        &lt;!&ndash; 编码信息列 &ndash;&gt;-->
        <!--        <el-table-column label="编码信息" prop="codeMessage" align="center" min-width="395px"-->
        <!--                         fixed="left">-->

        <!--        </el-table-column>-->


        <!-- 商品信息列 -->
        <el-table-column label="商品信息" prop="goodsMessage" align="center">
          <el-table-column label="sku名" width="120px">
            <template #default="scope">
              <el-input v-model="scope.row.skuName" size="small"/>
            </template>
          </el-table-column>
          <!--          <el-table-column label="sku编码" width="120px">-->
          <!--            <template #default="scope">-->
          <!--              <el-input v-model="scope.row.skuId" size="small"/>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="商品编码" width="80px">
            <template #default="scope">
              <el-table :data="scope.row.goods" style="width: 100%" :show-header="false"
                        size="small">
                <el-table-column prop="skuId"/>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="50px">
            <template #default="scope">
              <el-table :data="scope.row.goods" style="width: 100%" :show-header="false"
                        size="small">
                <el-table-column prop="count"/>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="图片" width="50px">
            <template #default="scope">
              <el-table :data="scope.row.goods" style="width: 100%" :show-header="false"
                        size="small">
                <el-table-column prop="name" style="padding-left: 20px">
                  <template #default="scopes">
                    <image-preview :src="scopes.row.pic" :width="20" :height="20"/>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="140px">
            <template #default="scope">
              <el-table :data="scope.row.goods" style="width: 100%" :show-header="false"
                        size="small">
                <el-table-column prop="name" show-overflow-tooltip/>
              </el-table>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 产品完全成本列 -->
        <el-table-column label="产品成本" prop="fullProductCost" align="center">
          <el-table-column label="合计" prop="productSumCost" width="70px"/>
          <el-table-column label="订货价" width="60px">
            <template #default="scope">
              <el-table :data="scope.row.goods" style="width: 100%" :show-header="false"
                        size="small">
                <el-table-column prop="costPrice">
                  <template #default="goodsScope">
                    <span>{{ goodsScope.row.costPrice }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        </el-table-column>


        <el-table-column :label="fixedName1" width="60px" prop="fixedValue1">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.fixedValue1 }}</span>
          </template>
        </el-table-column>


        <el-table-column label="营销成本"  prop="marketingCost" align="center">
          <el-table-column :label="fixedName2" width="65px" prop="fixedValue2">
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.fixedValue2 }}</span>
            </template>
          </el-table-column>

          <el-table-column :label="fixedName3" width="65px" prop="fixedValue3">
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.fixedValue3 }}</span>
            </template>
          </el-table-column>

          <el-table-column :label="rateName1" width="65px" prop="rateValue1">
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.rateValue1 }}</span>
            </template>
          </el-table-column>

          <el-table-column :label="rateName2" width="65px" prop="rateValue2">
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.rateValue2 }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="rateName3" width="65px" prop="rateValue3">
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.rateValue3 }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="discountName" width="65px" prop="discount">
            <template #default="scope">
              <span style="margin-left: 10px">{{ scope.row.discount }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="定价" prop="price" width="90px">
          <template #default="scope">
            <el-input v-model="scope.row.price" size="small"/>
          </template>
        </el-table-column>

        <!-- 成本汇总列 -->
        <el-table-column label="成本合计" width="80px" prop="summaryConst" align="center">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.summaryConst }}</span>
          </template>
        </el-table-column>

        <!-- 定价列 -->
        <el-table-column label="sku利润" width="80px" prop="skuProfit">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.skuProfit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="sku利润率" width="100px" prop="profitMargin">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.profitMargin + '%' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="sku毛利率" width="100px" prop="grossProfitMargin">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.grossProfitMargin + '%' }}</span>
          </template>
        </el-table-column>


        <el-table-column label="投产" width="100px" prop="productionMargin">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.productionMargin + '%' }}</span>
          </template>
        </el-table-column>

        <!-- 销售量列 -->
        <el-table-column label="销售量" prop="saleCount" width="80px">
          <template #default="scope">
            <el-input v-model.number="scope.row.saleCount" size="small"/>
          </template>
        </el-table-column>


        <el-table-column label="总利润" prop="profit">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.profit }}</span>
          </template>
        </el-table-column>


        <!-- 操作列 -->
        <el-table-column label="操作" fixed="right" width="60">
          <template #default="scope">
            <el-button size="small" type="text" @click="deleteSku(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 按商品编码添加SKU弹窗 -->
    <el-dialog title="按商品编码添加sku" v-model="goodsVisible" append-to-body width="30%">
      <el-table :data="skuForm.goods" size="small">
        <el-table-column label="商品编码">
          <template #default="scope">
            <el-input v-model.trim="scope.row.skuId" placeholder="请输入商品编码（区分大小写）"/>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="scope">
            <el-input-number :min="1" v-model.number="scope.row.count" size="small"
                             placeholder="请输入数量"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :width="100">
          <template #default="scope">
            <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" plain size="small" style="width: 100%" @click="addRow">新增
      </el-button>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="goodsVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSkuByGoods">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 按组合编码添加SKU弹窗 -->
    <el-dialog title="按组合编码添加sku" v-model="combineVisible" append-to-body width="20%">
      <el-form ref="skuFormRef" :model="skuForm" :rules="skuFormRules" size="small">
        <el-form-item label="组合编码" prop="skuId">
          <el-input v-model.trim="skuForm.skuId" placeholder="请输入组合编码"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="combineVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSkuByCombine">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>
</template>


<script setup>
// 导入API
import {PriceLinkApi} from '@/api/business/operation/price/link'
import {PriceConfigApi} from "@/api/business/operation/price/config";
import {useUserStore} from "@/store/modules/user";


const message = useMessage() // 消息弹窗
// 定义组件 emits
const emit = defineEmits(['success'])

// 响应式变量定义
const drawerRef = ref(null) // 抽屉引用
const formRef = ref(null) // 主表单引用
const skuFormRef = ref(null) // 组合编码表单引用

// 弹窗显示控制
const visible = ref(false)
const goodsVisible = ref(false)
const combineVisible = ref(false)


// 优惠参数
const fixedValue1 = ref(null)
const fixedValue2 = ref(null)
const fixedValue3 = ref(null)
const rateValue1 = ref(null)
const rateValue2 = ref(null)
const rateValue3 = ref(null)
const discount = ref(null)


const fixedName1 = ref(null)
const fixedName2 = ref(null)
const fixedName3 = ref(null)
const rateName1 = ref(null)
const rateName2 = ref(null)
const rateName3 = ref(null)
const discountName = ref(null)


// 初始表单数据工厂函数
const getInitialFormData = () => ({
  linkId: null,
  iid: null,
  linkName: null,
  userId: null,
  fixedValue1: null,
  fixedValue2: null,
  fixedValue3: null,
  rateValue1: null,
  rateValue2: null,
  rateValue3: null,
  discount: null,
})

const form = ref(getInitialFormData())


// 商品编码表单数据
const skuForm = ref({
  skuId: null,
  goods: [
    {skuId: null, count: 1}
  ]
})

// 批量处理表格数据
const skuList = ref([])
const batchTable = ref([])
const currentRow = ref(null)


// 表单校验规则
const rules = ref({
  linkId: [{required: true, message: '请填写链接id', trigger: 'blur'}],
  linkName: [{required: true, message: '请填写链接名称', trigger: 'blur'}],
  shopId: [{required: true, message: '请选择店铺', trigger: 'blur'}]
})

const skuFormRules = ref({
  skuId: [{required: true, message: '请输入组合编码', trigger: 'blur'}]
})


/**
 * 计算SKU单价相关字段（成本、定价、利润等）
 * @param {Array} list - SKU列表
 */
const updateCalculatePrices = (list) => {
  list.forEach(item => {

    // 比例值1 = 定价 * 比例值1%
    item.rateValue1 = (parseFloat(item.price || 0) * (rateValue1.value || 0) / 100).toFixed(2)

    // 比例值2 = 定价 * 比例值2%
    item.rateValue2 = (parseFloat(item.price || 0) * (rateValue2.value || 0) / 100).toFixed(2)

    // 比例值3
    item.rateValue3 = (parseFloat(item.price || 0) * (rateValue3.value || 0) / 100).toFixed(2)

    // 固定值1
    item.fixedValue1 = parseFloat(fixedValue1.value || 0).toFixed(2)

    // 固定值2
    item.fixedValue2 = parseFloat(fixedValue2.value || 0).toFixed(2)

    // 固定值3
    item.fixedValue3 = parseFloat(fixedValue3.value || 0).toFixed(2)

    // 折扣优惠 = 定价 - 定价 * (折扣/10)（默认折扣10）
    item.discount = (
      parseFloat(item.price || 0) -
      (parseFloat(item.price || 0) * (parseFloat(discount.value || 10) / 10))
    ).toFixed(2)

    // 成本汇总 = 产品成本 + 快递费 + 扣点 + 新客礼金
    item.summaryConst = (
      parseFloat(item.productSumCost || 0) +
      parseFloat(item.fixedValue1 || 0) +
      parseFloat(item.fixedValue2 || 0) +
      parseFloat(item.fixedValue3 || 0) +
      parseFloat(item.rateValue1 || 0) +
      parseFloat(item.rateValue2 || 0) +
      parseFloat(item.rateValue3 || 0) +
      parseFloat(item.discount || 0)
    ).toFixed(2)

    // SKU利润 = 定价 - 成本汇总
    item.skuProfit = (
      parseFloat(item.price || 0) -
      parseFloat(item.summaryConst || 0)
    ).toFixed(2)


    // SKU利润率 = (利润 / 定价) * 100%（避免除零）
    item.profitMargin = item.skuProfit && parseFloat(item.skuProfit) !== 0
      ? ((parseFloat(item.skuProfit || 0) / parseFloat(item.price)) * 100).toFixed(2)
      : '0'

    // SKU毛利率=(1- (成本/定价))*100%
    item.grossProfitMargin = item.productSumCost && parseFloat(item.productSumCost) !== 0 &&
    item.price && parseFloat(item.price) !== 0 ?
      ((1 - (parseFloat(item.productSumCost || 0) / parseFloat(item.price))) * 100).toFixed(2) : '0'

    //投产 = 1/利润率
    item.productionMargin = item.profitMargin && parseFloat(item.profitMargin) !== 0
      ? ((1 / parseFloat(item.profitMargin)) * 100).toFixed(2) : 0

    // 总利润 = 销售量 * SKU利润
    item.profit = (parseInt(item.saleCount || 0) * parseFloat(item.skuProfit || 0)).toFixed(2)
  })
}


/**
 * 计算表单汇总字段（总销售额、总利润、总利润率）
 * @param {Array} list - SKU列表
 */
const updateCalculateForm = (list) => {

  // 总利润 = 所有SKU利润之和
  form.value.profit = list.reduce((sum, item) => {
    console.log(item.profit)
    const profit = parseFloat(item.profit || 0)
    return isNaN(profit) ? sum : sum + profit
  }, 0).toFixed(2)

  // 总销售额 = 所有SKU（最终售价 * 销售量）之和
  form.value.sales = list.reduce((sum, item) => {
    const price = parseFloat(item.price || 0)
    const volume = parseFloat(item.saleCount || 0)
    return (isNaN(price) || isNaN(volume)) ? sum : sum + (price * volume)
  }, 0).toFixed(2)

  // 总利润率 = (总利润 / 总销售额) * 100%（避免除零）
  form.value.profitMargin = form.value.sales && parseFloat(form.value.sales) !== 0
    ? ((parseFloat(form.value.profit || 0) / parseFloat(form.value.sales)) * 100).toFixed(2)
    : '0'
}


// 监听优惠参数和SKU列表变化,自动计算
watch(
  [() => fixedValue1, () => fixedValue2, () => fixedValue3, () => rateValue1, () => rateValue2, () => rateValue3, () => discount, () => skuList.value],
  () => {
    updateCalculatePrices(skuList.value)
    updateCalculateForm(skuList.value)
  },
  {deep: true, immediate: true}
)

const userStore = useUserStore()

/**
 * 生成8位随机数字
 */
const generateRandomLinkId = () => {
  return Math.floor(10000000 + Math.random() * 90000000).toString()
}

/**
 * 打开核算抽屉
 * @param {Object} row - 编辑时的行数据
 */
const open = async (row) => {
  // 重置参数
  fixedValue1.value = null
  fixedValue2.value = null
  fixedValue3.value = null
  rateValue1.value = null
  rateValue2.value = null
  rateValue3.value = null
  discount.value = null
  resetForm()
  await getConfig()

  // 显示抽屉
  visible.value = true

  // userId默认是自己
  form.value.userId = userStore.user.id;

  // 编辑模式：加载数据
  if (row) {
    const link = await PriceLinkApi.getPriceLink(row.id)
    // 赋值表单数据
    form.value.linkId = link.linkId
    form.value.iid = link.iid
    form.value.linkName = link.linkName
    form.value.userId = link.userId
    form.value.shopId = link.shopId
    form.value.remark = link.remark
    fixedValue1.value = link.fixedValue1 || null
    fixedValue2.value = link.fixedValue2 || null
    fixedValue3.value = link.fixedValue3 || null
    rateValue1.value = link.rateValue1 || null
    rateValue2.value = link.rateValue2 || null
    rateValue3.value = link.rateValue3 || null
    discount.value = link.discount || null
    skuList.value = link.erpGoodsVOList || []
  } else {
    // 新增模式：生成8位随机数字作为linkId
   // form.value.linkId = generateRandomLinkId()
  }
}


const variables = {
  fixedName1,
  fixedName2,
  fixedName3,
  rateName1,
  rateName2,
  rateName3,
  discountName,
  fixedValue1,
  fixedValue2,
  fixedValue3,
  rateValue1,
  rateValue2,
  rateValue3,
  discount,
};

/**
 * 获取配置参数
 */
const getConfig = async () => {
  let queryParams = {
    pageNo: 1,
    pageSize: 1000,
    configKey: '标准'
  }
  const data = await PriceConfigApi.getPriceConfigPage(queryParams)
  // 查找 configKey 为"标准"的配置
  if (data.list && data.list.length > 0) {
    const jdConfig = data.list.find(item => item.configKey === '标准')
    if (jdConfig && jdConfig.configValue) {
      try {
        // 解析 JSON 字符串
        const configData = JSON.parse(jdConfig.configValue)

        // 设置名称和值
        rateName1.value = configData.rateName1 || null
        rateValue1.value = configData.rateValue1 || null
        rateName2.value = configData.rateName2 || null
        rateValue2.value = configData.rateValue2 || null
        rateName3.value = configData.rateName3 || null
        rateValue3.value = configData.rateValue3 || null
        fixedName1.value = configData.fixedName1 || null
        fixedValue1.value = configData.fixedValue1 || null
        fixedName2.value = configData.fixedName2 || null
        fixedValue2.value = configData.fixedValue2 || null
        fixedName3.value = configData.fixedName3 || null
        fixedValue3.value = configData.fixedValue3 || null

        // 折扣默认值
        discountName.value = '折扣'
        discount.value = 10
      } catch (error) {
        console.error('解析配置失败:', error)
        message.error('配置格式错误')
      }
    }
  }
}

/**
 * 抽屉关闭前回调
 * @param {Function} done - 关闭回调
 */
const handleBeforeClose = (done) => {
  ElMessageBox.confirm('确认关闭吗？')
    .then(() => {
      resetForm()
      done()
    })
    .catch(() => {
    })
}

/**
 * 重置表单
 */
const resetForm = () => {
  // 重置主表单 - 使用 Object.assign 保持响应式
  form.value = getInitialFormData()

  // 重置商品编码表单
  skuForm.value = {
    skuId: null,
    goods: [{skuId: null, count: 1}]
  }

  // 重置列表
  skuList.value = []
  batchTable.value = []
}

/**
 * 打开按商品编码添加SKU弹窗
 */
const openGoodsDialog = () => {
  goodsVisible.value = true
  skuForm.value.goods = [{skuId: null, count: 1}]
}

/**
 * 打开按组合编码添加SKU弹窗
 */
const openCombineDialog = () => {
  combineVisible.value = true
  skuForm.value.skuId = null
}


/**
 * 按商品编码添加SKU
 */
const addSkuByGoods = () => {

  PriceLinkApi.addSkuByGoodsCode(skuForm.value).then(res => {
    skuList.value.push(res)
    goodsVisible.value = false
  })
}

/**
 * 按组合编码添加SKU
 */
const addSkuByCombine = () => {
  skuFormRef.value.validate((valid) => {
    if (valid) {
      PriceLinkApi.addSkuByCombineCode(skuForm.value).then(res => {
        skuList.value.push(res)
        combineVisible.value = false
      })
    }
  })
}

/**
 * 删除单个SKU
 * @param {Object} row - 要删除的SKU行
 */
const deleteSku = (row) => {
  const index = skuList.value.findIndex(item => item === row)
  if (index !== -1) {
    skuList.value.splice(index, 1)
  }
}


/**
 * 清空所有SKU
 */
const clearAllSku = () => {
  skuList.value = []
}

/**
 * 新增商品编码行
 */
const addRow = () => {
  skuForm.value.goods.push({skuId: null, count: 1})
}

/**
 * 删除商品编码行
 * @param {Object} row - 要删除的行
 */
const deleteRow = (row) => {
  const index = skuForm.value.goods.findIndex(item => item === row)
  if (index !== -1) {
    skuForm.value.goods.splice(index, 1)
  }
}

/**
 * 表格单元格样式（亏损时标红）
 * @param {Object} param0 - 单元格参数
 * @returns {Object} 样式对象
 */
const handleCellStyle = ({row, column}) => {
  // 将字符串转换为数字再比较
  if (parseFloat(row.skuProfit || 0) < 0) {
    const redStyle = {backgroundColor: '#fef0f0', color: '#f56c6c'}
    switch (column.property) {
      case 'skuProfit':
      case 'profitMargin':
      case 'profit':
      case 'grossProfitMargin':
      case 'productionMargin':
        return redStyle
      default:
        return {}
    }
  }
  return {}
}

/**
 * 表头样式（分区域着色）
 * @param {Object} param0 - 表头参数
 * @returns {Object} 样式对象
 */
const handleHeaderCellStyle = ({column}) => {
  const colorMap = {
    // 编码和商品信息
    codeMessage: '#d0dfe6',
    goodsMessage: '#ede3e7',

    // 成本相关
    fullProductCost: '#93b5cf',


    // 定价和销量
    price: '#c6e6e8',
    saleCount: '#9ee9ec',

    // 优惠参数
    fixedValue1: '#a2c6d4',
    superPrice: '#a2c6d4',
    marketingCost: '#add6e8',
    summaryConst: '#a2c6d4',


    // 利润指标
    skuProfit: '#d3e3fd',
    profitMargin: '#dde7e9',
    grossProfitMargin: '#efece7',
    productionMargin: '#d5dee3',
    profit: '#d5d9d8'
  }
  return colorMap[column.property] ? {
    backgroundColor: colorMap[column.property],
    color: '#606266'
  } : {color: '#606266'}
}


/**
 * 保存链接信息
 */
const saveLink = async () => {
  try {
    // 1. 调用 validate 并等待验证结果（使用 Promise 形式，不加回调）
    const valid = await formRef.value.validate();
    if (valid && checkSkuList()) {
      console.log(skuList.value);
      // 2. 组装表单数据（保持不变）
      form.value.erpGoodsVOList = skuList.value;
      form.value.fixedValue1 = parseFloat(fixedValue1.value);
      form.value.fixedValue2 = parseFloat(fixedValue2.value);
      form.value.fixedValue3 = parseFloat(fixedValue3.value);
      form.value.rateValue1 = parseFloat(rateValue1.value);
      form.value.rateValue2 = parseFloat(rateValue2.value);
      form.value.rateValue3 = parseFloat(rateValue3.value);
      form.value.discount = parseFloat(discount.value);

      // 3. 提交保存（await 生效，因为在 async 函数中）
      await PriceLinkApi.savePricingInfo(form.value);
      visible.value = false;
      message.success('操作成功');
      emit('success'); // 通知父组件刷新
    }
  } catch (error) {
    // 4. 验证失败时的处理（如表单校验不通过）
    console.log('表单验证失败', error);
    message.error('请完善表单信息');
  }
};

/**
 * 校验SKU列表（非空、必填项）
 * @returns {boolean} 校验结果
 */
const checkSkuList = () => {
  if (skuList.value.length === 0) {
    ElMessage.error('sku数量不能为空')
    return false
  }

  for (let i = 0; i < skuList.value.length; i++) {
    const sku = skuList.value[i]
    if (!sku.skuName) {
      ElMessage.error(`第${i + 1}行错误：sku名不能为空`)
      return false
    }
    if (!sku.price) {
      ElMessage.error(`第${i + 1}行错误：定价不能为空`)
      return false
    }
  }
  return true
}


// 暴露组件方法（供父组件调用）
defineExpose({open})

</script>

<style scoped>
/* 自定义输入框样式 */
.group {
  position: relative;
}

.input {
  font-size: 12px;
  padding: 10px 10px 5px 5px;
  display: block;
  width: 70px;
  border: none;
  border-bottom: 1px solid #515151;
  background: transparent;
  text-align: center;
}

.input:focus {
  outline: none;
}

label {
  color: #999;
  font-size: 12px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 5px;
  top: 10px;
  transition: 0.2s ease all;
  -moz-transition: 0.2s ease all;
  -webkit-transition: 0.2s ease all;
}

.input:focus ~ label,
.input:valid ~ label {
  top: -10px;
  left: 0;
  font-size: 13px;
  color: #5264AE;
}

.bar {
  position: relative;
  display: block;
  width: 70px;
}

.bar:before,
.bar:after {
  content: '';
  height: 2px;
  width: 0;
  bottom: 1px;
  position: absolute;
  background: #5264AE;
  transition: 0.2s ease all;
  -moz-transition: 0.2s ease all;
  -webkit-transition: 0.2s ease all;
}


.bar:before {
  left: 50%;
}

.bar:after {
  right: 50%;
}

.input:focus ~ .bar:before,
.input:focus ~ .bar:after {
  width: 50%;
}

</style>
